﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace DicomLibrary.Rendering
{
    public class DRenderer2D
    {
        public static Bitmap RenderDImage(DFile dicomFile)
        {
            var pixelData = (ushort[])dicomFile.DataElements.Single(pd => pd.Tag.GroupNumber == 0x7FE0 && pd.Tag.ElementNumber == 0x0010).Value;
            var imageWidth = (ushort)dicomFile.DataElements.Single(pd => pd.Tag.GroupNumber == 0x0028 && pd.Tag.ElementNumber == 0x0010).Value;
            var imageHeight = (ushort)dicomFile.DataElements.Single(pd => pd.Tag.GroupNumber == 0x0028 && pd.Tag.ElementNumber == 0x0011).Value;

            int wWidth = 885;
            int wLevel = wWidth / 2;

            int minValue = wLevel - wWidth / 2;
            int maxValue = wLevel + wWidth / 2;

            Bitmap bmp = new Bitmap(imageWidth, imageHeight);
            for (int i = 0; i < pixelData.Length; i++)
            {
    

                int oColor;
                if (pixelData[i] < minValue)
                    oColor = 0;
                else if (pixelData[i] > maxValue)
                    oColor = 255;
                else if (pixelData[i] > 1000)
                    oColor = ((pixelData[i] - (wLevel - (wWidth / 2))) * 255) / wWidth;
                else
                    oColor = ((pixelData[i] - (wLevel - (wWidth / 2))) * 255) / wWidth;
                bmp.SetPixel(i % imageWidth, (i / imageHeight), Color.FromArgb(oColor, oColor, oColor));
            }
            return bmp;
        }
    }
}
